package com.ppx.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ppx.dao.InfoDao;
import com.ppx.pojo.CityData;
import com.ppx.pojo.ProvinceData;
import com.ppx.util.JsoupStatic;
import com.ppx.util.JsoupTool;
import com.ppx.util.TopAndEndStringReplace;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author wangxiaotao
 * @create 2021-05-26-9:58
 */
@Service
public class FirstTaskImpl implements com.ppx.service.FirstTask {
	@Autowired
	private InfoDao infoDao;

	@Scheduled(cron = "0 0 1 * * ?")//每天凌晨1点执行一次
	@Override
	public void getAllDataFromYXY() throws IOException {
		//初始化page
		JsoupTool.getPageByJSoup(JsoupStatic.URL,JsoupStatic.USER_AGENT,JsoupStatic.HOST,JsoupStatic.REFERER);
		//获取地区数据
		String recdata = JsoupTool.getStatisticInformation(JsoupStatic.AREA_INFORMATION_ATTRIBUTE);
		//去除前面和后面的多余字符串
		String reldata = TopAndEndStringReplace.changeGetAreaStat(recdata);
//		//新建list存放数据
//		List<ProvinceData> provinceDataList = new ArrayList<>();
		JSONArray objects = JSON.parseArray(reldata);
		for (int i = 0; i < objects.size(); i++) {
			//先转成JSON对象
			JSONObject jsonObject = (JSONObject) JSONObject.toJSON(objects.get(i));
			//json对象转java对象
			ProvinceData provinceData = JSON.toJavaObject(jsonObject, ProvinceData.class);
//			provinceDataList.add(provinceData);
			//日期format
			SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd");
			//更新省份总体数据
			infoDao.updataProvinceCountByProvinceData(provinceData, sdf.format(new Date()));
			//更新城市数据
			for(CityData cityData:provinceData.getCities()){
				if(cityData!=null){//判断是否为空
					infoDao.updataCityCountByAreaName(cityData,sdf.format(new Date()));
				}
			}
		}
		System.out.println("数据更新完成");
	}

}
